﻿using System.Reflection;
using System;
using System.ComponentModel;
using System.Diagnostics;

namespace Inovout.Descriptors
{
    public class PropertyDescriptor : MemberDescriptor, IValueGetter
    {
        private PropertyInfo propertyInfo;
        public PropertyDescriptor(PropertyInfo propertyInfo)
            : base(propertyInfo)
        {
            this.propertyInfo = propertyInfo;
        }
        public bool IsReadOnly
        {
            get { return !propertyInfo.CanWrite; }
        }
        public Type PropertyType
        {
            get { return propertyInfo.PropertyType; }
        }

        public object GetValue(object instance)
        {
            return propertyInfo.GetValue(instance, null);
        }

        public bool TryConvertValueFrom(object value, out object result)
        {
            result = null;
            TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(this.PropertyType);
            try
            {
                result = converter.ConvertFrom(value);
                return true;
            }
            catch (Exception ex)
            {
                Debugger.Log(1, "warning", ex.Message);
                return false;
            }
        }
        public object ConvertValueFrom(object value)
        {
            object result;
            TryConvertValueFrom(value, out result);
            return result;
        }
        public void SetValue(object instance, object value)
        {
            // if (propertyInfo.CanWrite)
            //  {
            propertyInfo.SetValue(instance, value, null);
            //   }
        }
    }
}
